#!/bin/bash
set -e

while getopts  ":w:c:p:g:f:" opts
do
	case  $opts  in
	w)
		window=$OPTARG
		;;
	g)
        ref_genome=$OPTARG
        ;;
	p)
        out_prefix=$OPTARG
        ;;
	f)
        filt=true
		f_arg=$OPTARG
        ;;
	\?)
		echo `basename $0` "[-w window_size] [-g ref_genome_file] [-p out_prefix] [-f filter_window_size] <sample.bam>"
		exit 1
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then
	echo `basename $0` '[-w window_size] [-g ref_genome_file] [-p out_prefix] [-f filter_window_size] <sample.bam>'
	exit 1
fi


#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------

if
samtools view -H $1 |grep -l '^@RG' > /dev/null
then
sample_name=`samtools view -H $1 |grep '^@RG' |perl -n -e 'if(/SM:(.+?)[\t|\n]/){print $1}'`
fi

chrom=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y

declare -A win_size;
win_size[1kb]=1000;
win_size[5kb]=5000;
win_size[10kb]=10000;
win_size[25kb]=25000;
win_size[50kb]=50000;
win_size[100kb]=100000;
win_size[200kb]=200000;
win_size[500kb]=500000;
win_size[1mb]=1000000;
win_size[2mb]=2000000;
win_size[5mb]=5000000;

:>$out_prefix.names.txt

for index in ${!win_size[@]}; do

if test -e $out_prefix.$index.txt; then
echo $out_prefix.$index.txt exists.
echo $out_prefix.$index.txt $index ${win_size[$index]} $sample_name >> $out_prefix.names.txt
else
readCounter -c $chrom -w ${win_size[$index]} $1 > $out_prefix.$index.wig
cat $out_prefix.$index.wig |grep -v f > $out_prefix.$index.txt
echo $out_prefix.$index.txt $index ${win_size[$index]} $sample_name >> $out_prefix.names.txt
fi
done

Rscript ${tools_path}/script/lorenz_cnv.r --args $out_prefix.names.txt
# mv 1.lorenz.pdf $out_prefix.lorenz.pdf
rename lorenz $out_prefix.lorenz lorenz.pdf

Rscript ${tools_path}/script/hist_rc.r --args $out_prefix.50kb.txt $sample_name
mv 1.rc_hist.pdf $out_prefix.50kb.rc_hist.pdf
mv 1.rc_freq.pdf $out_prefix.50kb.rc_freq.pdf

Rscript ${tools_path}/script/hist_rc.r --args $out_prefix.200kb.txt $sample_name
mv 1.rc_hist.pdf $out_prefix.200kb.rc_hist.pdf
mv 1.rc_freq.pdf $out_prefix.200kb.rc_freq.pdf

Rscript ${tools_path}/script/hist_rc.r --args $out_prefix.1mb.txt $sample_name
mv 1.rc_hist.pdf $out_prefix.1mb.rc_hist.pdf
mv 1.rc_freq.pdf $out_prefix.1mb.rc_freq.pdf

# bak.sh $out_prefix.*.pdf